package com.example.pool.completableFuture;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import com.example.pool.httpTest.util.HttpClientUtil;
import com.example.pool.utils.ThreadPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
public class Test1 {
    private static ThreadPoolExecutor threadPool = ThreadPoolUtil.newFixedThreadPool(8,8,1000L,new ArrayBlockingQueue<>(10000),"tencentCloudSMS");

    static {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        List<Logger> loggerList = loggerContext.getLoggerList();
        loggerList.forEach(logger -> {logger.setLevel(Level.INFO);});
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long l = System.currentTimeMillis();
        log.info("开始时间：{}", l);
        int size = 10;
        CompletableFuture[] completables = new CompletableFuture[size];
        for (int i = 0; i < size; i++) {
            completables[i] = send(i);
        }
//        threadPool.shutdown(); //线程池关闭程序停止
        CompletableFuture.allOf(completables).get();
        log.info("总耗时:{}", System.currentTimeMillis() - l);
    }

    private static CompletableFuture send(int i) {
        log.info("send start, threadName:{}, 线程编号：{}", Thread.currentThread().getName(), i);
        CloseableHttpClient httpClient = HttpClientUtil.getHttpClient();
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
            final HttpGet request = new HttpGet("http://localhost:8080/get");
            try {
                HttpResponse response = httpClient.execute(request);
                String result = EntityUtils.toString(response.getEntity());
                System.out.println(Thread.currentThread().getName() + " : " + result);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, threadPool);
//        try {
//            voidCompletableFuture.get(); // get会阻塞进程，使异步变成同步。所以可以不写get。
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (ExecutionException e) {
//            e.printStackTrace();
//        }

        log.info("send end, threadName:{}, 线程编号：{}", Thread.currentThread().getName(), i);
        return voidCompletableFuture;
    }


}
